<template>
  <div class="home">
    <!-- 筛选 -->
    <div class="search_content">
      <van-nav-bar
        :title="$route.meta.title"
        left-text="返回"
        left-arrow
        @click-left="goBack"
      />
      <van-search
        v-model="requestParams.codeNo"
        placeholder="请输入客户名称或联系电话"
        shape="round"
        @search="initData"
        @clear="clearSearch"
      />
      <div class="search_item">
        <van-dropdown-menu :close-on-click-outside="false">
          <van-dropdown-item title="状态" ref="statusRef">
            <div class="searchbox">
              <div class="title">线索状态</div>
              <div class="insureList">
                <div
                  class="insure_item"
                  :class="item.check ? 'active' : ''"
                  v-for="(item, index) in leadsBillStatusList"
                  :key="index"
                  @click="handleSearchSelect(index, 'leadsBillStatusList')"
                >
                  {{ item.name }}
                </div>
              </div>
              <div class="title">跟进状态</div>
              <div class="insureList">
                <div
                  class="insure_item"
                  :class="item.check ? 'active' : ''"
                  v-for="(item, index) in followBillStatusList"
                  :key="index"
                  @click="handleSearchSelect(index, 'followBillStatusList')"
                >
                  {{ item.name }}
                </div>
              </div>
              <div class="title">评估状态</div>
              <div class="insureList">
                <div
                  class="insure_item"
                  :class="item.check ? 'active' : ''"
                  v-for="(item, index) in estimateBillStatusList"
                  :key="index"
                  @click="handleSearchSelect(index, 'estimateBillStatusList')"
                >
                  {{ item.name }}
                </div>
              </div>

              <div class="insureBtn">
                <van-button
                  size="small"
                  type="warning"
                  class="resetBtn"
                  @click="handleSearchReset()"
                >
                  重置
                </van-button>
                <van-button
                  size="small"
                  type="info"
                  class="confirmBtn"
                  @click="onConfirm('statusRef')"
                >
                  确认
                </van-button>
              </div>
            </div>
          </van-dropdown-item>

          <van-dropdown-item title="线索来源" ref="filterRef">
            <div class="searchbox">
              <div class="insureList">
                <div
                  class="insure_item"
                  :class="item.check ? 'active' : ''"
                  v-for="(item, index) in leadsSourceList"
                  :key="index"
                  @click="handleSearchSelect(index, 'leadsSourceList')"
                >
                  {{ item.name }}
                </div>
              </div>
              <div class="insureBtn">
                <van-button
                  size="small"
                  type="warning"
                  class="resetBtn"
                  @click="handleSearchXsReset()"
                >
                  重置
                </van-button>
                <van-button
                  size="small"
                  type="info"
                  class="confirmBtn"
                  @click="onConfirm('filterRef')"
                >
                  确认
                </van-button>
              </div>
            </div>
          </van-dropdown-item>

          <van-dropdown-item title="筛选" ref="detailRef">
            <div class="searchbox timebox">
              <div class="title">线索提交时间</div>
              <div class="flex">
                <van-field
                  class="time_item"
                  v-model="requestParams.taskStartCreateTime"
                  label=""
                  :placeholder="'开始时间'"
                  input-align="right"
                  readonly
                  @click="handleSelectTime('taskStartCreateTime')"
                />
                -
                <van-field
                  class="time_item"
                  v-model="requestParams.taskEndCreateTime"
                  label=""
                  :placeholder="'结束时间'"
                  input-align="right"
                  readonly
                  @click="handleSelectTime('taskEndCreateTime')"
                />
              </div>
              <van-form>
                <van-field
                  v-model="requestParams.leasdProvicePersonName"
                  label="线索提供人"
                  :placeholder="'请输入'"
                  input-align="right"
                />
                <van-field
                  v-model="requestParams.leasdFollowPersonName"
                  label="线索跟进人"
                  :placeholder="'请输入'"
                  input-align="right"
                />
              </van-form>

              <div class="insureBtn">
                <van-button
                  size="small"
                  type="warning"
                  class="resetBtn"
                  @click="handleAccidentReset()"
                >
                  重置
                </van-button>
                <van-button
                  size="small"
                  type="info"
                  class="confirmBtn"
                  @click="onConfirm('detailRef')"
                >
                  确认
                </van-button>
              </div>
            </div>
          </van-dropdown-item>
        </van-dropdown-menu>

        <!-- 服务顾问下拉 -->
        <van-popup v-model="showSelectPicker" position="bottom">
          <van-picker
            show-toolbar
            :columns="columns"
            @confirm="handleSelectConfirm"
            @cancel="showSelectPicker = false"
            value-key="name"
          />
        </van-popup>
        <!-- 时间选择 -->
        <van-popup v-model="showPickerDate" position="bottom">
          <van-datetime-picker
            v-model="currentDate"
            type="date"
            @cancel="onCancelDate"
            @confirm="onConfirmDate"
            :formatter="formatter"
          />
        </van-popup>
      </div>
    </div>

    <!-- 列表 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="loadData"
        v-if="recordList && recordList.length != 0"
      >
        <div class="orderList">
          <div class="flex" v-for="(item, index) in recordList" :key="index">
            <div class="taskCheck" v-if="showTransmitFlag">
              <van-checkbox
                v-model="item.check"
                shape="square"
                icon-size="15px"
              ></van-checkbox>
            </div>
            <div class="orderItem">
              <div class="orderItem_header">
                <div class="orderItem_lt" @click="goDetail(item)">
                  <div class="carNo">{{ item.customerName }}</div>
                </div>
                <div class="orderItem_rt">
                  跟进人：{{ item.followName ? item.followName : '-' }}
                </div>
              </div>
              <div class="orderItem_content" @click="goDetail(item)">
                <div class="orderItem_data full">
                  <div class="order_label">车型</div>
                  <div class="txt">
                    {{ item.carModelName ? item.carModelName : '-' }}
                  </div>
                </div>
                <div class="orderItem_data full">
                  <div class="order_label">展厅</div>
                  <div class="txt">
                    {{ item.showOrgName ? item.showOrgName : '-' }}
                  </div>
                </div>
                <div class="orderItem_data">
                  <div class="order_label">线索来源</div>
                  <div class="txt">
                    {{ item.leadsSource ? item.leadsSource : '-' }}
                  </div>
                </div>
                <div class="orderItem_data">
                  <div class="order_label">创建时间</div>
                  <div class="txt">{{ item.bizDate ? item.bizDate : '-' }}</div>
                </div>
                <div class="orderItem_data">
                  <div class="order_label">线索提供人</div>
                  <div class="txt">
                    {{ item.provideName ? item.provideName : '-' }}
                  </div>
                </div>
                <div class="orderItem_data">
                  <div class="order_label">下次跟进时间</div>
                  <div class="txt">
                    {{ item.nextFollowTime ? item.nextFollowTime : '-' }}
                  </div>
                </div>
              </div>
              <div class="orderItem_footer">
                <div class="orderItem_status" v-if="item.followBillStatus">
                  {{ item.followBillStatus }}
                </div>
                <div class="orderItem_status" v-if="item.leadsBillStatus">
                  {{ item.leadsBillStatus }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </van-list>
      <van-empty class="noContent" description="暂无数据" v-else />
    </van-pull-refresh>

    <div class="addBtn">
      <div class="footerBtn orderItem_filebox" @click="handleAdd">新增线索</div>
    </div>
  </div>
</template>

<script>
import { Search, DropdownMenu, DropdownItem, Empty, Dialog } from 'vant'
import taskApi from '@/api/taskApi'
import commonApi from '@/api/commonApi'
import { getCookies } from '@/utils/util.js'
import sellManageApi from '@/api/sellManageApi'

export default {
  name: 'repairOrder',
  components: {
    Search,
    DropdownMenu,
    DropdownItem,
    Empty,
    Dialog,
  },
  data() {
    return {
      value: '',
      carCouponList: [
        { name: '是', code: 1, check: false },
        { name: '否', code: 0, check: false },
      ],
      taskTypeList: [],
      statusList: [
        { name: '已处理', code: 1, check: false },
        { name: '未处理', code: 2, check: false },
      ],

      recordList: [
        // {
        //   billId: '', //单据ID
        //   customerName: '章三', //客户名称
        //   phone: '18123123', //客户电话
        //   carModelName: '阿迪', // 车型
        //   leadsBillStatus: '跟进', //线索状态
        //   followBillStatus: '跟进', //跟进状态
        //   followName: '章三啊', //线索跟进人
        //   provideName: '章三啊', // 线索提供人
        //   bizDate: '2020-09-09', // 创建日期
        //   nextFollowTime: '2020-09-09', //下次跟进日期
        // },
      ],
      columns: [],
      showSelectPicker: false,
      requestParams: {
        customerOrPhone: '', //客户名称或联系电话,非必填，String
        pageNo: 1, //页码，必填，int
        orgId: '', //登录组织ID,必填，String
        leadsBillStatus: '', //线索状态，非必填，String
        followBillStatus: '', //跟进状态，非必填，String
        estimateBillStatus: '', //评估状态，非必填，String
        leadsStartDate: '', //线索提交开始时间，非必填，String
        leadsEndDate: '', //线索提交结束时间，非必填，String
        leasdFollowPersonName: '', //线索跟进人，非必填，String
        leasdProvicePersonName: '', //线索提供人，非必填，String
        leadsSource: '',
        userId: getCookies('userId'), //用户ID，必填，String
      },
      carCouponIndex: null,

      repairCenterList: [
        { name: '厦门路虎', code: 1 },
        { name: '厦门捷豹', code: 2 },
      ],
      serviceList: [
        { name: '黄某某', code: 1 },
        { name: '张某某', code: 2 },
      ],
      delayList: [
        { name: '是', billId: 1, check: false },
        { name: '否', billId: 0, check: false },
      ],
      creatList: [
        { name: '是', billId: 1, check: false },
        { name: '否', billId: 0, check: false },
      ],
      defeatList: [
        { name: '是', billId: 1, check: false },
        { name: '否', billId: 0, check: false },
      ],

      delayIndex: null,
      creatIndex: null,
      defeatIndex: null,
      showTransmitFlag: false,
      timeField: '',
      showPickerDate: false,
      currentDate: new Date(),
      list: [],
      // 分页参数
      loading: false,
      finished: false,
      refreshing: false,
      isLoadData: false,

      field: '',
      fieldName: '',
      fixCenterList: [],
      twoBillStatusList: [],
      leadsBillStatusList: [],
      followBillStatusList: [],
      estimateBillStatusList: [],
      leadsSourceList: [],
    }
  },

  mounted() {
    this.getLeadsBillStatus()
    this.getFollowBillStatus()
    this.getEstimateBillStatus()
    this.getLeadsSource()
    this.getEmpPerson()
    this.initData()
  },

  watch: {
    $route: {
      handler: function (val, oldVal) {
        if (val && val.query && val.query.type) {
          this.initData()
        }
      },
      deep: true,
      immediate: false,
    },
  },

  methods: {
    // 初始化列表
    initData() {
      this.requestParams.pageNo = 1
      this.loadData()
    },
    // 获取列表
    loadData() {
      if (this.isLoadData) return
      this.isLoadData = true
      this.loading = true
      this.finished = false
      // console.log(this.isLoadData);
      sellManageApi
        .secondHandCarFacade({
          ...this.requestParams,
          method: 'getPurchaseLeadsList',
        })
        .then((res) => {
          if (this.requestParams.pageNo == 1) {
            this.recordList = res.data || []
          } else {
            this.recordList = this.recordList.concat(res.data || [])
          }
          this.requestParams.pageNo += 1

          if (res.data && res.data.length < 10) {
            this.finished = true
            this.isLoadData = true
          }
          this.isLoadData = false
          this.loading = false
        })
    },
    // 下拉刷新
    onRefresh() {
      // 清空列表数据
      this.recordList = []
      this.finished = false
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true
      this.refreshing = false
      this.initData()
    },
    // 获取任务类型
    getTaskType() {
      commonApi
        .getTaskType({ userId: this.requestParams.userId })
        .then((res) => {
          this.taskTypeList = this.formatCheckData(res.data)
        })
    },
    // 获取维修中心
    getMainFixCenter() {
      commonApi
        .getMainFixCenter({
          userId: this.requestParams.userId,
          type: 'fixCenter',
        })
        .then((res) => {
          this.fixCenterList = res.data
        })
    },
    // 获取服务顾问
    getEmpPerson() {
      commonApi
        .getEmpPerson({
          fixCenterId: '',
          userId: this.requestParams.userId,
        })
        .then((res) => {
          this.serviceList = res.data
        })
    },
    // 获取线索状态
    getLeadsBillStatus() {
      commonApi
        .getEnums({ key: 'leadsBillStatus', userId: this.requestParams.userId })
        .then((res) => {
          if (res.data) {
            this.leadsBillStatusList = this.formatCheckData(res.data)
          }
        })
    },
    // 获取线索跟进状态
    getFollowBillStatus() {
      commonApi
        .getEnums({
          key: 'followBillStatus',
          userId: this.requestParams.userId,
        })
        .then((res) => {
          if (res.data) {
            this.followBillStatusList = this.formatCheckData(res.data)
          }
        })
    },
    // 获取评估状态
    getEstimateBillStatus() {
      commonApi
        .getEnums({
          key: 'estimateBillStatus',
          userId: this.requestParams.userId,
        })
        .then((res) => {
          if (res.data) {
            this.estimateBillStatusList = this.formatCheckData(res.data)
          }
        })
    },
    // 获取线索来源
    getLeadsSource() {
      commonApi
        .getEnums({
          key: 'leadsSource',
          userId: this.requestParams.userId,
        })
        .then((res) => {
          if (res.data) {
            this.leadsSourceList = this.formatCheckData(res.data)
          }
        })
    },

    // 格式化多选数据
    formatCheckData(data) {
      data.forEach((item) => {
        item.check = false
      })
      return data
    },

    // 选择下拉
    handleSelect(field, fieldName) {
      this.showSelectPicker = true
      if (field == 'carCoupon') {
        this.columns = [
          { name: '是', value: 1 },
          { name: '否', value: 2 },
        ]
      } else if (field == 'outUser') {
        this.columns = [
          { name: '服务人员1', value: 1 },
          { name: '服务人员2', value: 2 },
        ]
      } else if (field == 'fixCenterId') {
        this.columns = this.fixCenterList
      }
      this.field = field
      this.fieldName = fieldName
    },

    // 筛选是否
    handleCarSelect(index) {
      this.carCouponIndex = index
    },
    // 筛选重置
    handleSelectReset() {
      this.requestParams.taskPersonId = ''
      this.requestParams.isGenRepBook = ''
    },

    // 选择下拉确认
    handleSelectConfirm(value, index) {
      this.requestParams[this.field] = value.billId
      this.requestParams[this.fieldName] = value.name
      if (this.field == 'fixCenterId') {
        this.getEmpPerson()
      }
      this.showSelectPicker = false
    },

    // 所属服务顾问重置
    handleReset() {
      this.requestParams.fixCenterId = ''
      this.requestParams.outUser = ''
    },

    //时间重置
    handleAccidentReset() {
      this.requestParams.leasdProvicePersonName = ''
      this.requestParams.leasdFollowPersonName = ''
      this.requestParams.leadsEndDate = ''
      this.requestParams.leadsStartDate = ''
    },
    onConfirm(ref) {
      this.$refs[ref].toggle()
      if (ref == 'statusRef') {
        this.requestParams.leadsBillStatus = this.getCheckData(
          this.leadsBillStatusList,
        ).join(';')
        this.requestParams.followBillStatus = this.getCheckData(
          this.followBillStatusList,
        ).join(';')
        this.requestParams.estimateBillStatus = this.getCheckData(
          this.estimateBillStatusList,
        ).join(';')
      }
      if (ref == 'filterRef') {
        this.requestParams.leadsSource = this.getCheckData(
          this.leadsSourceList,
        ).join(';')
      }
      this.initData()
    },
    // 获取选中的数据
    getCheckData(list) {
      let checkList = []
      list.forEach((el) => {
        if (el.check) {
          checkList.push(el.value)
        }
      })
      return checkList
    },
    // 时间确认
    onConfirmDate() {
      this.requestParams[
        this.timeField
      ] = `${this.value1}-${this.value2}-${this.value3}` // 字符串拼接 结果入2020-07-03
      this.onCancelDate()
    },
    onCancelDate() {
      this.showPickerDate = false
    },

    // 日期组件自定义格式
    formatter(type, value) {
      if (type === 'year') {
        this.value1 = value // 可以拿到当前点击的数值
        return `${value}年`
      } else if (type === 'month') {
        this.value2 = value
        return `${value}月`
      }
      this.value3 = value
      return `${value}日`
    },

    // 获取list名称
    getFieldName(list, key, val) {
      if (list && list.length > 0) {
        let obj = list.filter((item) => {
          return item[key] == val
        })
        if (obj.length > 0) {
          return obj[0].name
        }
      }
      return null
    },

    // 详情
    goDetail(data) {
      localStorage.setItem('billId', data.billId)
      this.$router.push({
        path: '/assessManageDetail',
        // query: { billId: data.billId },
      })
    },
    // 新增
    handleAdd() {
      this.$router.push({
        path: '/assessManageEdit',
      })
    },
    // 顶部筛选选择数据
    handleSearchSelect(index, listKey) {
      this[listKey][index].check = !this[listKey][index].check
    },
    // 重置
    handleSearchReset() {
      this.leadsBillStatusList.forEach((item) => {
        item.check = false
      })
      this.followBillStatusList.forEach((item) => {
        item.check = false
      })
      this.estimateBillStatusList.forEach((item) => {
        item.check = false
      })
    },
    // 线索重置
    handleSearchXsReset() {
      this.leadsSourceList.forEach((item) => {
        item.check = false
      })
    },

    // 是否数据选择
    handleIsSelect(index, key, list, field) {
      this[key] = index
      this.requestParams[field] = this[list][index].billId
    },
    // 任务转交展示
    handleShowTransmit() {
      this.showTransmitFlag = true
    },
    // 确认转交
    handleTransmitSubmit() {},
    // 取消
    handleTransmitCancel() {
      this.showTransmitFlag = false
    },
    // 时间筛选
    handleSelectTime(field) {
      this.timeField = field
      this.showPickerDate = true
    },
    clearSearch() {
      this.requestParams.codeNo = ''
      this.initData()
    },
    goBack() {
      localStorage.setItem('skipUrl', '')
      this.$router.push('/home')
    },
  },
}
</script>

<style lang="less" scoped="">
body {
  background: #f3f3f3;
}
.search_content {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 2;
}
.timebox {
  /deep/.van-cell::after {
    border: none;
  }
  .time_item {
    /deep/.van-field__control--right {
      border: 1px solid #d1d1d1;
      padding: 0.1rem 0;
      text-align: center;
      border-radius: 3px;
    }
  }
}
.full {
  width: 100% !important;
}
.searchbox {
  padding: 0.3rem;
  .title {
    font-size: 0.3rem;
    font-weight: bold;
    color: #333;
    margin-bottom: 0.2rem;
    padding-top: 0.2rem;
  }
  .insureList {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-wrap: wrap;
    .insure_item {
      border: 1px solid #999;
      text-align: center;
      padding: 0.15rem 0rem;
      width: 30%;
      box-sizing: border-box;
      // margin-right: 0.1rem;
      font-size: 0.26rem;
      border-radius: 3px;
      color: #666;
      margin-bottom: 0.2rem;
      margin-right: 5%;
      &:nth-child(3n) {
        margin-right: 0;
      }
      &.active {
        border: 1px solid #f65e07;
        color: #f65e07;
      }
    }
  }
  .insureBtn {
    display: flex;
    justify-content: right;
    margin-top: 0.4rem;
    .resetBtn {
      padding: 0 0.4rem;
      margin-right: 0.2rem;
    }
    .confirmBtn {
      padding: 0 0.4rem;
    }
  }
}

.orderList {
  padding-top: 148px;
  margin: 0.2rem;
  overflow: hidden;
  // width: 100%;
  // padding-bottom: 1.5rem;
  .taskCheck {
    margin-right: 0.1rem;
  }
  .orderItem {
    padding: 0.3rem;
    background: #fff;
    border-radius: 10px;
    margin-bottom: 0.3rem;
    width: 100%;

    .orderItem_header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 0.3rem;
      padding-bottom: 0.2rem;
      border-bottom: 1px solid #f6f6f6;
      position: relative;
      .orderItem_lt {
        .carNo {
          font-size: 0.3rem;
          color: #333;
          margin-right: 0.2rem;
          font-weight: bold;
        }

        .carStatus {
          background: #35bc04;
          color: #fff;
          border-radius: 4px;
          padding: 0.1rem 0.2rem;
          font-size: 0.24rem;
          text-align: center;
          width: 1rem;
          margin-top: 0.1rem;
        }
      }
      .orderItem_rt {
        display: flex;
        align-items: center;
        align-self: center;
        justify-content: flex-start;
        color: #666;
        font-size: 0.28rem;

        .txt {
          font-size: 0.28rem;
          color: #161616;
        }
        .icon-tel {
          color: #fff;
          background: #35bc04;
          font-size: 0.32rem;
          padding: 0.1rem;
          border-radius: 50%;
          margin-right: 0.2rem;
        }
        .icon-wx {
          color: #409eff;
          font-size: 0.65rem;
        }
      }
    }
    .orderItem_content {
      display: flex;
      justify-content: flex-start;
      flex-wrap: wrap;
      align-items: center;
      .orderItem_data {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        width: 50%;
        margin-bottom: 0.2rem;
        font-size: 0.28rem;
        box-sizing: content-box;
        color: #333;
        .order_label {
          font-size: 0.28rem;
          color: #999;
          margin-right: 0.1rem;
        }
        .txt {
          font-size: 0.28rem;
          color: #333;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        &.time {
          width: 100%;
        }
      }
    }
    .orderItem_footer {
      display: flex;
      justify-content: space-between;
      border-top: 1px solid #f6f6f6;
      padding-top: 0.2rem;
      .orderItem_status {
        background: #35bc04;
        color: #fff;
        font-size: 0.24rem;
        padding: 0.08rem 0.15rem;
        border-radius: 3px;
      }
    }
    .orderItem_file {
      background: #ebebeb;
      color: #333;
      border-radius: 5px;
      padding: 0.2rem 0;
      text-align: center;
      width: 100%;
      font-size: 0.28rem;
      display: flex;
      align-items: center;
      justify-content: center;
      .file_item {
        width: 33.33%;
        border-right: 1px solid #ccc;
        .icon-tel {
          font-size: 0.34rem;
          color: #35bc04;
          margin-right: 0.1rem;
        }
        .icon-mileage {
          font-size: 0.4rem;
          color: #409eff;
          margin-right: 0.1rem;
          position: relative;
          top: 0.04rem;
        }
        .icon-gw {
          font-size: 0.4rem;
          color: #409eff;
          margin-right: 0.1rem;
          position: relative;
          top: 0.04rem;
        }
        &:last-child {
          border: none;
        }
      }
    }
  }
}
.addBtn {
  position: fixed;
  bottom: 0.8rem;
  width: 100%;
  z-index: 1;
  .footerBtn {
    width: 2.8rem;
    margin: auto;
    text-align: center;
    font-size: 0.28rem;
    padding: 0.25rem 0rem;
    border-radius: 50px;
  }
  .orderItem_filebox {
    margin: auto;
    background: #409eff;
    color: #fff;
  }
  .comfirmBtn {
    background: #409eff;
    color: #fff;
  }
  .cancelBtn {
    border: 1px solid #ccc;
    color: #999;
    background: #fff;
  }
}
.noContent {
  margin-top: 2rem;
}
</style>
